
// const wrtc = require('wrtc');
const {RTCPeerConnection} = require('wrtc');

function registerSocket(io) {
	// 处理前端发送的offer
	io.on('connection', socket => {
  console.log("connection===>socket 连接成功");
  
		socket.on('offer', async offer => {
			try {
				// 创建一个新的RTCPeerConnection对象
				const peerConnection = new RTCPeerConnection()

				// 处理ICE candidate
				peerConnection.onicecandidate = event => {
					if (event.candidate) {
						// 将ice candidate发送到前端
						socket.emit('candidate', event.candidate)
					}
				}

				// 处理远程媒体流
				peerConnection.ontrack = event => {
					// 这里可以处理接收到的媒体流，例如保存到文件或进行转码
				}

				// 设置远程描述
				await peerConnection.setRemoteDescription(offer)

				// 创建一个answer并设置为本地描述
				const answer = await peerConnection.createAnswer()
				await peerConnection.setLocalDescription(answer)

				// 将answer发送到前端
				socket.emit('answer', answer)
			} catch (error) {
				console.error('处理offer失败:', error)
			}
		})

		// 处理前端发送的ICE candidate
		socket.on('candidate', candidate => {
			// 将ice candidate添加到RTCPeerConnection中
			// 这里假设你有一个全局的peerConnection对象
			peerConnection.addIceCandidate(candidate)
		})
	})
}

module.exports = registerSocket

/**
 * 便用 peer 搭建信令服务器
const {PeerServer} = require('peer')
const peerserver= PeerServer((port:3001,path: '/myPeerserver'))

前端也需要引入peer.js
var peer = new Peer();
// Every Peer object is assigned a random, unique ID when it's created.
peer.on('open', function(id) {
 console.log('My peer ID is: ' + id);
});

// Call a peer, providing our mediaStream
var call = peer.call('dest-peer-id',	mediaStream);  

call.on('stream', function(stream) {
// `stream` is the MediaStream of the remote peer.
// Here you'd add it to an HTML video/canvas element.
});  
 */
